package Candidate;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import login.UserModel;
import static org.imgscalr.Scalr.*;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.imgscalr.Scalr;

import Eclass.EclassForm;
import Eclass.Score.ScoreForm;
import Forum.ForumThreadForm;
import Master.SchoolForm;

public class CandidateAction extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String month, year, noUrutan;

		CandidateForm cForm = (CandidateForm) form;
		CandidateManager cMan = new CandidateManager();
		HttpSession session = request.getSession(true);
		UserModel user = (UserModel) session.getAttribute("userLogin");

		boolean flag = false;
		boolean statusReset = false;
		boolean statusSend = false;
		Integer statusAction = null;
		String[] regNo;
		String[] regNoNew;
		String[] jobCode;
		String[] status;
		String[] fullName;
		String[] photoName;
		String regisNo = "";
		String pathPhoto = "";
		String note = "", fullname="", regNO = "", lastStatus = "", jobCODE;
		String userId = "", validUser = "";

		System.out.println("TASK ================ "+cForm.getTask());
		// --------------------------------------------------------------
		// Navigation ----------------------------------------------------------
		// CandidateForm candidateForm = new CandidateForm();
		SchoolForm schoolForm = new SchoolForm();
		EclassForm eClassForm = new EclassForm();
		ForumThreadForm forumForm = new ForumThreadForm();
		ScoreForm scoreForm = new ScoreForm();
		
//		if ("manageTrainee".equalsIgnoreCase(cForm.getTask())) {
//			eClassForm.setTask("manageTrainee");
//			return mapping.findForward("eclass");
//		} else 
		if ("batch".equalsIgnoreCase(cForm.getTask())) {
			eClassForm.setTask("batch");
			return mapping.findForward("eclass");
		} else if ("listExamPrep".equalsIgnoreCase(cForm.getTask())) {
			eClassForm.setTask("listExamPrep");
			return mapping.findForward("eclass");
		} else if ("manageSchool".equalsIgnoreCase(cForm.getTask())) {
			schoolForm.setTask("manageSchool");
			return mapping.findForward("master");
		} else if ("forumPage".equalsIgnoreCase(cForm.getTask())) {
			forumForm.setTask("forumPage");
			return mapping.findForward("forum");
		} else if ("report".equalsIgnoreCase(cForm.getTask())) {
			scoreForm.setTask("report");
			return mapping.findForward("score");
		}
		// ------------------------------------------------------------------------------------------------------------------------------

		// --willian--------------
		if ("manageTrainee".equalsIgnoreCase(cForm.getTask())) {
			cForm.setListBatch(cMan.getBatch());
			return mapping.findForward("manageTrainee");
		}
		if ("viewTrainee".equalsIgnoreCase(cForm.getTask())) {
			cForm.setcModel(cMan.viewTrainee(cForm.getTraineeId()));

			return mapping.findForward("viewTrainee");
		}
		// -------------------
		if ("checkRegistration".equalsIgnoreCase(cForm.getTask())) {
			if(cForm.getEmailCandidate()!="" || cForm.getIdCardNum()!= ""){

			regisNo = cMan.getRegCheck(cForm.getEmailCandidate(),cForm.getIdCardNum(),cForm.getUserIdCardNum());
			
			if(regisNo==null){
				statusAction = 1;
			}else{
			Date date = new Date();
			SimpleDateFormat sdf = null;
			sdf = new SimpleDateFormat("yy");
			year = sdf.format(date);

			sdf = new SimpleDateFormat("MM");
			month = sdf.format(date);
			
				regNo = regisNo.split("-");

				if((Integer.parseInt(month) != Integer.parseInt(regNo[2]) || ((Integer.parseInt(month) - Integer.parseInt(regNo[2]))<=4 && (Integer.parseInt(month) - Integer.parseInt(regNo[2]))>0) || ((Integer.parseInt(regNo[2]) - Integer.parseInt(month))<=4 && (Integer.parseInt(regNo[2]) - Integer.parseInt(month))>0)) && (Integer.parseInt(regNo[1]) >=Integer.parseInt(year))){
					statusAction = 1;
				}else{
					statusAction = 0;
				}
			}
			
			}else{
				statusAction = 1;
			}

			response.setContentType("text/text;charset=utf-8");
			response.setHeader("cache-control", "no-cache");
			PrintWriter out = response.getWriter();
			
			out.write(statusAction.toString());
			 
			out.flush();

			return null;
		}
		if ("accountSetting".equalsIgnoreCase(cForm.getTask())) {
			cForm.getcModel().setUserId(user.getUserid());
			cForm.getcModel().setPassword(user.getPassword());

			int width = 100;
			int height = 50;
			Random rdm = new Random();
			int rl = rdm.nextInt();

			String hash1 = Integer.toHexString(rl);

			String capstr = hash1.substring(0, 5);

			session.setAttribute("key", capstr);

			Color background = new Color(204, 204, 204);

			Color fbl = new Color(77, 165, 209);

			Font fnt = new Font("SansSerif", 1, 27);

			BufferedImage cpimg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);

			Graphics g = cpimg.createGraphics();

			g.setColor(background);

			g.fillRect(0, 0, width, height);

			g.setColor(fbl);

			g.setFont(fnt);

			g.drawString(capstr, 10, 25);

			g.setColor(background);

			g.drawLine(10, 17, 80, 17);

			g.drawLine(10, 22, 80, 22);

			response.setContentType("image/jpeg");

			File fileToCreate = new File(getServlet().getServletContext().getRealPath("/") + "images\\", "captcha.jpeg");
			OutputStream strm = new FileOutputStream(fileToCreate);
			ImageIO.write(cpimg, "jpeg", strm);
			strm.close();

			return mapping.findForward("accountSetting");
		}
		if("editAccount".equalsIgnoreCase(cForm.getTask())) {
			flag = cMan.updateAccount(cForm.getcModel());

			if (flag == true) {
				session.setAttribute("result", "Password Successfully Updated");
				cForm.setcModel(cMan.selectCandidateWithOther(user.getUserid()));
			}else{
				session.setAttribute("result", "Password Not Successfully Updated");
			}
			return mapping.findForward("welcome");
		}
		if("checkOldPassword".equalsIgnoreCase(cForm.getTask())){
			statusAction = cMan.checkPasswordUser(user.getUserid(),cForm.getPassword());
			response.setContentType("text/text;charset=utf-8");
			response.setHeader("cache-control", "no-cache");
			PrintWriter out = response.getWriter();
			out.write(statusAction.toString());
			out.flush();

			return null;
		}
		if("uploadPhoto".equalsIgnoreCase(cForm.getTask())) {	
			try {
				regNo = cForm.getcModel().getRegNo();
				jobCode = cForm.getcModel().getJobCode();
				
				regisNo = regNo[0]+"-"+regNo[1]+"-"+regNo[2]+"-";
				if(regNo[3].substring(3,3).equals("")){
					regNo[3]=regNo[3].substring(0,3);
				}
				FormFile myFile = cForm.getPhotoFile();

				String type[] = myFile.getContentType().split("image/");

				String fileName = regisNo+regNo[3]+"."+type[1];

				byte[] fileData = myFile.getFileData();
				
				if (Integer.toHexString(fileData[0] & 0xFF).equalsIgnoreCase("ff")&& Integer.toHexString(fileData[1] & 0xFF).equalsIgnoreCase("d8")) {
					String directoryPath = "Photo\\";
					cForm.getcModel().setPhotoPath(directoryPath);

					String filePath = getServlet().getServletContext().getRealPath("/") + directoryPath;
					ByteArrayInputStream in = new ByteArrayInputStream(fileData);
					pathPhoto = directoryPath + fileName;
	
					File fileToCreate = new File(filePath, fileName);

					BufferedImage image = ImageIO.read(in);
					if (image.getWidth() > 151 || image.getHeight() > 227) {
						image = Scalr.resize(image, Method.ULTRA_QUALITY,Mode.FIT_EXACT, 151, 227);
						if (!fileToCreate.exists()) {
							ImageIO.write(image, "jpeg", fileToCreate);
						} else {
							fileToCreate.deleteOnExit();
							ImageIO.write(image, "jpeg", fileToCreate);
						}
					} else {
						if (!fileToCreate.exists()) {
							FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
							fileOutStream.write(myFile.getFileData());
							fileOutStream.flush();
							fileOutStream.close();
						} else {
							fileToCreate.deleteOnExit();
							FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
							fileOutStream.write(myFile.getFileData());
							fileOutStream.flush();
							fileOutStream.close();
						}
					}

					request.setAttribute("pathUploadResult",pathPhoto.replaceAll("\\\\", "/"));
					request.setAttribute("fileName", fileName);
					cForm.setListJob(cMan.selectAllJob());
					cForm.setListSchoolName(cMan.selectAllSchoolData());
					cForm.setListCity(cMan.selectAllCityData());
					cForm.setListBatch(cMan.selectAllBatchData());

					if (cForm.getNomor() == 1) {
						request.setAttribute("curYear", regNo[1]);
						request.setAttribute("curMonth", regNo[2]);
						request.setAttribute("regNo", regNo[3]);

						return mapping.findForward("insertCandidate");
					} else if (cForm.getNomor() == 2) {

						request.setAttribute("regNo1", regNo[0]);
						request.setAttribute("regNo2", regNo[1]);
						request.setAttribute("regNo3", regNo[2]);
						request.setAttribute("regNo4", regNo[3]);
						request.setAttribute("photo", null);
						request.setAttribute("jobCode1", jobCode[0]);
						request.setAttribute("jobCode2", jobCode[1]);
						request.setAttribute("lastStatus", cForm.getcModel().getLastStatus());
		
						if (cForm.getcModel().getTechTestDate() != null) {
							request.setAttribute("techTestDate", cForm.getcModel().getTechTestDate());
						} else {
							request.setAttribute("techTestDate", "");
						}
						if (cForm.getcModel().getBirthDte() != null) {
							request.setAttribute("birthDate", cForm.getcModel().getBirthDte());
						} else {
							request.setAttribute("birthDate", "");
						}
						if (cForm.getcModel().getGender() != ""|| cForm.getcModel().getGender() != null) {
							request.setAttribute("gender", cForm.getcModel().getGender());
						}
						if (cForm.getcModel().getReligion() != ""|| cForm.getcModel().getReligion() != null) {
							request.setAttribute("religion", cForm.getcModel().getReligion());
						}
						if (cForm.getcModel().getMaritalStatus() != ""|| cForm.getcModel().getMaritalStatus() != null) {
							request.setAttribute("maritalStatus", cForm.getcModel().getMaritalStatus());
						}
						if (cForm.getcModel().getSchoolCity() != ""|| cForm.getcModel().getSchoolCity() != null) {
							request.setAttribute("schoolCity", cForm.getcModel().getSchoolCity());
						}
						if (cForm.getcModel().getEducationLevel() != ""|| cForm.getcModel().getEducationLevel() != null) {
							request.setAttribute("eduLevel", cForm.getcModel().getEducationLevel());
						}

						cForm.setListSchoolName(cMan.selectAllSchoolData());
						cForm.setListJob(cMan.selectAllJob());
						cForm.setListBatch(cMan.selectAllBatchData());
						cForm.setListCity(cMan.selectAllCityData());
						
						return mapping.findForward("updateCandidate");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				session.setAttribute("result", "Photo not successfully uploaded");
			}
		}
		if("profileSetting".equalsIgnoreCase(cForm.getTask())) {
			cForm.setcModel(cMan.selectCandidateWithOther(user.getUserid()));
			if(cForm.getcModel().getPhoto()!=null || cForm.getcModel().getPhoto()!=""){
			request.setAttribute("photoPath", cForm.getcModel().getPhoto());
			}else{
			request.setAttribute("photoPath", null);	
			}
			return mapping.findForward("detailCandidate");
		}
		if("detail".equalsIgnoreCase(cForm.getTask())) {
			cForm.setcModel(cMan.selectCandidateWithOther(cForm.getcModel().getUserId()));
			if(cForm.getcModel().getPhoto()!=null || cForm.getcModel().getPhoto()!=""){
				request.setAttribute("photoPath", cForm.getcModel().getPhoto());
				}else{
				request.setAttribute("photoPath", null);	
				}
			return mapping.findForward("detailCandidate");
		}
		if ("reset".equalsIgnoreCase(cForm.getTask())) {
			flag=cMan.resetCandidate(cForm.getcModel().getUserId());
			statusReset = cMan.resetTechTest(cForm.getcModel().getUserId());

			if(flag==true && statusReset ==true){
				if(user.getRole().equalsIgnoreCase("admin")){
					cForm.setcModel(cMan.selectCandidateWithOther(cForm.getcModel().getUserId()));
					}else if(user.getRole().equalsIgnoreCase("candidate")){	
						cForm.setcModel(cMan.selectCandidateWithOther(user.getUserid()));
					}
					if("Empty".equalsIgnoreCase(cForm.getcModel().getCity())){
						cForm.getcModel().setCity("");
					}
					if("Empty".equalsIgnoreCase(cForm.getcModel().getSchoolCity())){
						cForm.getcModel().setSchoolCity("");
					}
					if("Empty".equalsIgnoreCase(cForm.getcModel().getSchoolName())){
						cForm.getcModel().setSchoolName("");
					}
					if (cForm.getcModel().getSchoolId() == null && cForm.getcModel().getSchoolName() !=null) {
						cForm.getcModel().setSchoolCityId(cMan.getCityId(cForm.getcModel().getSchoolCity()));
					}
					
					jobCode = cForm.getcModel().getJobCd().split("-");
					cForm.getcModel().setJobCode(jobCode);
					
					regNo = cForm.getcModel().getRegisNo().split("-");

					for (int i = 0; i < regNo.length; i++) {
						request.setAttribute("regNo" + (i + 1), regNo[i]);
					} 
					if(cForm.getcModel().getPhoto()!=null ){
					photoName = cForm.getcModel().getPhoto().split("/");
						request.setAttribute("fileName", photoName[1]);
						request.setAttribute("photo", cForm.getcModel().getPhoto());
					}else{
						request.setAttribute("fileName", null);
						request.setAttribute("photo", null);
					}
					request.setAttribute("jobCode1", jobCode[0]);
					request.setAttribute("jobCode2", jobCode[1]);
					request.setAttribute("birthDate", cForm.getcModel().getBirthDte());
					request.setAttribute("uploadPath", "");
					request.setAttribute("lastStatus", cForm.getcModel().getLastStatus());
					if (cForm.getcModel().getTechTestScore() != null&& cForm.getcModel().getLastStatus().equalsIgnoreCase("No Status")) {
						cMan.updateLastStatus(cForm.getcModel().getRegisNo());
						cForm.getcModel().setLastStatus("Technical Test");
					}
					if (cForm.getcModel().getTechTestDate() != null) {
						request.setAttribute("techTestDate", cForm.getcModel().getTechTestDate());
					} else {
						request.setAttribute("techTestDate", "");
					}
					if (cForm.getcModel().getGender() != ""|| cForm.getcModel().getGender() != null) {
						request.setAttribute("gender", cForm.getcModel().getGender());
					}
					if (cForm.getcModel().getReligion() != ""|| cForm.getcModel().getReligion() != null) {
						request.setAttribute("religion", cForm.getcModel().getReligion());
					}
					if (cForm.getcModel().getMaritalStatus() != ""|| cForm.getcModel().getMaritalStatus() != null) {
						request.setAttribute("maritalStatus", cForm.getcModel().getMaritalStatus());
					}
					if (cForm.getcModel().getSchoolCity() != ""|| cForm.getcModel().getSchoolCity() != null) {
						request.setAttribute("schoolCity", cForm.getcModel().getSchoolCity());
					}
					if (cForm.getcModel().getEducationLevel() != ""|| cForm.getcModel().getEducationLevel() != null) {
						request.setAttribute("eduLevel", cForm.getcModel().getEducationLevel());
					}
					cForm.setListSchoolName(cMan.selectAllSchoolData());
					cForm.setListJob(cMan.selectAllJob());
					cForm.setListBatch(cMan.selectAllBatchData());
					cForm.setListCity(cMan.selectAllCityData());
					
					session.setAttribute("result","Data has been reset");
			}else{
					session.setAttribute("result","Data can't be reset");
			}
			return mapping.findForward("updateCandidate");
		}
		if ("insert".equalsIgnoreCase(cForm.getTask())) {

			Date date = new Date();

			SimpleDateFormat sdf = null;
			sdf = new SimpleDateFormat("yy");
			year = sdf.format(date);

			sdf = new SimpleDateFormat("MM");
			month = sdf.format(date);
			noUrutan = cMan.getRegNo();

			request.setAttribute("curYear", year);
			request.setAttribute("curMonth", month);
			request.setAttribute("regNo", noUrutan);

			cForm.getcModel().setGradYear(null);
			cForm.setListJob(cMan.selectAllJob());
			cForm.setListSchoolName(cMan.selectAllSchoolData());
			cForm.setListCity(cMan.selectAllCityData());
			cForm.setListBatch(cMan.selectAllBatchData());
			
			return mapping.findForward("insertCandidate");
		}
		if ("update".equalsIgnoreCase(cForm.getTask())) {			
			if(user.getRole().equalsIgnoreCase("admin")){
				cForm.setcModel(cMan.selectCandidateWithOther(cForm.getcModel().getUserId()));
			}else if(user.getRole().equalsIgnoreCase("candidate")){
				cForm.setcModel(cMan.selectCandidateWithOther(user.getUserid()));
			}
			if("Empty".equalsIgnoreCase(cForm.getcModel().getCity())){
				cForm.getcModel().setCity("");
			}
			if("Empty".equalsIgnoreCase(cForm.getcModel().getSchoolCity())){
				cForm.getcModel().setSchoolCity("");
			}
			if("Empty".equalsIgnoreCase(cForm.getcModel().getSchoolName())){
				cForm.getcModel().setSchoolName("");
			}
			if (cForm.getcModel().getSchoolId() == null && cForm.getcModel().getSchoolName() !=null) {
				cForm.getcModel().setSchoolCityId(cMan.getCityId(cForm.getcModel().getSchoolCity()));
			}

			jobCode = cForm.getcModel().getJobCd().split("-");
			cForm.getcModel().setJobCode(jobCode);
			regNo = cForm.getcModel().getRegisNo().split("-");

			for (int i = 0; i < regNo.length; i++) {
				request.setAttribute("regNo" + (i + 1), regNo[i]);
			}
			 if(cForm.getcModel().getPhoto()==null||cForm.getcModel().getPhoto()=="null"){
				 request.setAttribute("fileName", null);
				 request.setAttribute("photo", null);
			 }else{
			photoName = cForm.getcModel().getPhoto().split("/");
			request.setAttribute("fileName", photoName[1]);
			request.setAttribute("photo", cForm.getcModel().getPhoto());
			request.setAttribute("pathUploadResult", null);
			}
			request.setAttribute("jobCode1", jobCode[0]);
			request.setAttribute("jobCode2", jobCode[1]);
			request.setAttribute("birthDate", cForm.getcModel().getBirthDte());	
			request.setAttribute("uploadPath", "");
			request.setAttribute("lastStatus", cForm.getcModel().getLastStatus());

			if (cForm.getcModel().getTechTestScore() != null && cForm.getcModel().getLastStatus().equalsIgnoreCase("No Status")) {
				cMan.updateLastStatus(cForm.getcModel().getRegisNo());
				cForm.getcModel().setLastStatus("Technical Test");
			}

			if (cForm.getcModel().getTechTestDate() != null) {
				request.setAttribute("techTestDate", cForm.getcModel().getTechTestDate());
			} else {
				request.setAttribute("techTestDate", "");
			}
			if (cForm.getcModel().getGender() != ""|| cForm.getcModel().getGender() != null) {
				request.setAttribute("gender", cForm.getcModel().getGender());
			}
			if (cForm.getcModel().getReligion() != ""|| cForm.getcModel().getReligion() != null) {
				request.setAttribute("religion", cForm.getcModel().getReligion());
			}
			if (cForm.getcModel().getMaritalStatus() != ""|| cForm.getcModel().getMaritalStatus() != null) {
				request.setAttribute("maritalStatus", cForm.getcModel().getMaritalStatus());
			}
			if (cForm.getcModel().getSchoolCity() != ""|| cForm.getcModel().getSchoolCity() != null) {
				request.setAttribute("schoolCity", cForm.getcModel().getSchoolCity());
			}
			if (cForm.getcModel().getEducationLevel() != ""|| cForm.getcModel().getEducationLevel() != null) {
				request.setAttribute("eduLevel", cForm.getcModel().getEducationLevel());
			}

			cForm.setListSchoolName(cMan.selectAllSchoolData());
			cForm.setListJob(cMan.selectAllJob());
			cForm.setListBatch(cMan.selectAllBatchData());
			cForm.setListCity(cMan.selectAllCityData());

			return mapping.findForward("updateCandidate");
		}
		if ("exportExcel".equalsIgnoreCase(cForm.getTask())) {
			ExportExcel e = new ExportExcel();
			List listCandidate = null;
			listCandidate = cMan.getAcceptedCandidate("Accepted", cForm.getBatchId());

			String contentType = "application/vnd.ms-excel";
			response.setContentType(contentType);
			response.setHeader("Content-Disposition","attachment; filename=QualifiedCandidate.xls");

			e.exportToExcel(listCandidate, response);
			if (user.getUserid().compareTo("super.admin") != 0) {
				cForm.setcModel(cMan.selectCandidateWithOther(user.getUserid()));
				request.setAttribute("path", cForm.getcModel().getPhoto());
			} else {
				cForm.setListBatch(cMan.selectBatch());
				cForm.setListCandidate(cMan.selectAllCandidate(cForm));
			}
			return mapping.findForward("listCandidate");
		}
		if ("updateCandidate".equalsIgnoreCase(cForm.getTask())) {
			jobCode = cForm.getcModel().getJobCode();
			jobCODE = jobCode[0] + "-" + jobCode[1];
			cForm.getcModel().setJobCd(jobCODE);
			
			if(cForm.getcModel().getBatchId()==null){
				cForm.getcModel().setBatchId(cMan.getBatchId(jobCode[1]));
				}
			regNo = cForm.getcModel().getRegNo();

			for (int i = 0; i < regNo.length - 1; i++) {

				regNO += regNo[i] + "-";
			}
			regNO += regNo[regNo.length - 1];
			cForm.getcModel().setRegisNo(regNO);
			
			if (cForm.getcModel().getLastStatus() == null) {
				lastStatus = "No Status";
				cForm.getcModel().setLastStatus(lastStatus);
			}else if (cForm.getcModel().getLastStatus().equalsIgnoreCase("Accepted")) {
				cForm.getcModel().setActiveCandidate(0);
			}else{
				cForm.getcModel().setActiveCandidate(1);
			}
			
			fullName = cForm.getcModel().getFullName().split(" ");

			if (fullName.length == 2) {
				cForm.getcModel().setFirstName(fullName[0]);
				cForm.getcModel().setLastName(fullName[1]);
			}else if(fullName.length > 1){
				for(int i=0;i<=fullName.length-3;i++){
					fullname+=fullName[i]+" ";
				}
				fullname+=fullName[fullName.length-2];
				cForm.getcModel().setFirstName(fullname);
				cForm.getcModel().setLastName(fullName[fullName.length-1]);
			}else if(fullName.length == 1) {
				cForm.getcModel().setFirstName(fullName[0]);
			}
			if (cForm.getSelectOtherCity().compareTo("yes") == 0) {
				if (user.getRole() == "admin") {
					cMan.insertCity(cForm.getcModel());
					cForm.getcModel().setCityId(cMan.getCityId(cForm.getcModel().getCity()));
				} else {
					cForm.getcModel().setCityId(null);
					note += "city::" + cForm.getcModel().getCity();
				}
			}else{
				note += "city::Empty";
			}

			if (cForm.getSelectOtherSchool().compareTo("yes") == 0) {

				if (cForm.getSelectOtherSchCity().compareTo("yes") == 0) {
					cForm.getcModel().setCity(cForm.getcModel().getSchoolCity());
					if (user.getRole() == "admin") {
						cMan.insertCity(cForm.getcModel());
						cForm.getcModel().setSchoolCityId(cMan.getCityId(cForm.getcModel().getSchoolCity()));
						cMan.insertSchool(cForm.getcModel());
						cForm.getcModel().setSchoolId(cMan.getSchoolId(cForm.getcModel().getSchoolName()));
					} else {
						note += "?!@!?SchoolCity::"+ cForm.getcModel().getSchoolCity();
					}
				} else {
					if (user.getRole() == "admin") {
						cMan.insertSchool(cForm.getcModel());
						cForm.getcModel().setSchoolId(cMan.getSchoolId(cForm.getcModel().getSchoolName()));
					} else {
						cForm.getcModel().setSchoolCity(cMan.getCity(cForm.getcModel().getSchoolCityId()));
						note += "?!@!?SchoolCity::"+ cForm.getcModel().getSchoolCity();
					}
				}
				cForm.getcModel().setSchoolId(null);
				note += "?!@!?SchoolName::" + cForm.getcModel().getSchoolName();
			} else {
				note += "?!@!?SchoolCity::Empty?!@!?SchoolName::Empty";
			}

			if (user.getRole().equalsIgnoreCase("candidate")){
				cForm.getcModel().setNote(note);
			}
			if (cForm.getcModel().getSchoolId() == null|| cForm.getcModel().getSchoolId() == 0) {
				cForm.getcModel().setSchoolId(null);
			}
			if (cForm.getcModel().getCityId() == null|| cForm.getcModel().getCityId() == 0) {
				cForm.getcModel().setCityId(null);
			}
			if (cForm.getcModel().getGradYear() == null|| cForm.getcModel().getGradYear() == 0) {
				cForm.getcModel().setGradYear(null);
			}
			if (cForm.getcModel().getGpa() == null|| cForm.getcModel().getGpa() == 0) {
				cForm.getcModel().setGpa(null);
			}
			if (cForm.getcModel().getTechTestScore() == null|| cForm.getcModel().getTechTestScore() == 0) {
				cForm.getcModel().setTechTestScore(null);
			}
			if(cForm.getcModel().getLastStatus().equalsIgnoreCase("Accepted")){
				cMan.insertAccCand(cForm.getcModel());
				cForm.getcModel().setActiveCandidate(0);
			}
			System.out.println("PHOTO : "+cForm.getcModel().getPhoto());
			flag = cMan.updateCandidate(cForm.getcModel());

			if (flag == true) {
				session.setAttribute("result","Candidate Data Successfully Updated");
				if (user.getUserid().compareTo("super.admin") != 0) {
					cForm.setcModel(cMan.selectCandidateWithOther(user.getUserid()));
					request.setAttribute("path", cForm.getcModel().getPhoto());
				} else {
					cForm.setListBatch(cMan.selectBatch());
					cForm.setListCandidate(cMan.selectAllCandidate(cForm));
				}

			}else{
				session.setAttribute("result","Candidate Data Not Successfully Updated");
			}

			return mapping.findForward("listCandidate");

		}
		if ("cancel".equalsIgnoreCase(cForm.getTask())) {
			if(cForm.getNomor() == 3){
				if (user.getUserid().compareTo("super.admin") != 0) {
					cForm.setcModel(cMan.selectCandidateWithOther(user.getUserid()));
					request.setAttribute("path", cForm.getcModel().getPhoto());
				} else {
					cForm.setListBatch(cMan.selectBatch());
					cForm.setListCandidate(cMan.selectAllCandidate(cForm));
				}
			}else if(cForm.getNomor() == 4){
				cForm.setcModel(cMan.selectCandidateWithOther(user.getUserid()));
				if(cForm.getcModel().getPhoto()!=null || cForm.getcModel().getPhoto()!=""){
				request.setAttribute("photoPath", cForm.getcModel().getPhoto());
				}else{
				request.setAttribute("photoPath", null);	
				}
				return mapping.findForward("detailCandidate");
			}if(cForm.getNomor() == 5){
				return mapping.findForward("welcome");
			}
			return mapping.findForward("listCandidate");
		}
		if ("sendEmail".equalsIgnoreCase(cForm.getTask())) {
			String emailTo = null;
			String emailFrom = "intanseptyliana@gmail.com";
			String passEmail = "september90";
			
			emailTo = cForm.getcModel().getTo();
			cForm.setEmailTo(emailTo);
			cForm.setEmailFrom(emailFrom);
			cForm.setPassEmail(passEmail);

			return mapping.findForward("sendEmail");

		}
		if ("send".equalsIgnoreCase(cForm.getTask()) && cForm.getNomor() == 1) {
			cForm.getcModel().setFrom(cForm.getEmailFrom());
			cForm.getcModel().setPassEmail(cForm.getPassEmail());
			
			SendEmail email = new SendEmail();
			
			statusSend = email.sendEmail(cForm.getcModel());
			
			if (statusSend == true) {
				session.setAttribute("result", "Email delivered");
			} else {
				session.setAttribute("result", "Email not delivered");
			}

			if (user.getUserid().compareTo("super.admin") != 0) {
				cForm.setcModel(cMan.selectCandidateWithOther(user.getUserid()));
				request.setAttribute("path", cForm.getcModel().getPhoto());
			} else {
				cForm.setListBatch(cMan.selectBatch());
				cForm.setListCandidate(cMan.selectAllCandidate(cForm));
			}
			
			return mapping.findForward("listCandidate");
		}
		if ("insertCandidate".equalsIgnoreCase(cForm.getTask())) {

			regNo = cForm.getcModel().getRegNo();
			jobCode = cForm.getcModel().getJobCode();
			jobCODE = jobCode[0] + "-" + jobCode[1];

			cForm.getcModel().setJobCd(jobCODE);
			if(cForm.getcModel().getBatchId()==null){
			cForm.getcModel().setBatchId(cMan.getBatchId(jobCode[1]));
			}
			
			for (int i = 0; i < regNo.length - 1; i++) {
				regNO += regNo[i] + "-";
			}
			cForm.getcModel().setRegisNo(regNO);
			
			if (cForm.getcModel().getStatus() == null) {
				lastStatus = "No Status";
			} else {
				status = cForm.getcModel().getStatus();
				lastStatus = status[status.length - 1];
			}
	
			cForm.getcModel().setLastStatus(lastStatus);

			validUser = generateUserId(cForm.getcModel().getFullName(),cForm,cMan);
			cForm.getcModel().setUserId(validUser.toLowerCase());
			cForm.getcModel().setPassword("ace");
			cForm.getcModel().setRole("candidate");
			cMan.insertMsUser(cForm.getcModel());

			if (cForm.getSelectOtherCity().compareTo("yes") == 0) {
				cMan.insertCity(cForm.getcModel());
				cForm.getcModel().setCityId(cMan.getCityId(cForm.getcModel().getCity()));
			}

			if (cForm.getSelectOtherSchool().compareTo("yes") == 0) {

				if (cForm.getSelectOtherSchCity().compareTo("yes") == 0) {
					cForm.getcModel().setCity(cForm.getcModel().getSchoolCity());
					cMan.insertCity(cForm.getcModel());
					cForm.getcModel().setSchoolCityId(cMan.getCityId(cForm.getcModel().getSchoolCity()));
					cMan.insertSchool(cForm.getcModel());
					cForm.getcModel().setSchoolId(cMan.getSchoolId(cForm.getcModel().getSchoolName()));
				} else {
					cMan.insertSchool(cForm.getcModel());
					cForm.getcModel().setSchoolId(cMan.getSchoolId(cForm.getcModel().getSchoolName()));
				}
			}

			if (cForm.getcModel().getSchoolId() == null|| cForm.getcModel().getSchoolId() == 0) {
				cForm.getcModel().setSchoolId(null);
			}
			if (cForm.getcModel().getCityId() == null|| cForm.getcModel().getCityId() == 0) {
				cForm.getcModel().setCityId(null);
			}
			if (cForm.getcModel().getGradYear() == null|| cForm.getcModel().getGradYear() == 0) {
				cForm.getcModel().setGradYear(null);
			}
			if (cForm.getcModel().getGpa() == null|| cForm.getcModel().getGpa() == 0) {
				cForm.getcModel().setGpa(null);
			}
			if (cForm.getcModel().getTechTestScore() == null|| cForm.getcModel().getTechTestScore() == 0) {
				cForm.getcModel().setTechTestScore(null);
			} 
			flag = cMan.insertCandidate(cForm.getcModel());

			if (flag == true) {
				session.setAttribute("result","Candidate Data Successfully Inserted");
			} else {
				session.setAttribute("result", "Data Not Successfully Inserted");
			}
			cForm.setListBatch(cMan.selectBatch());
			cForm.setListCandidate(cMan.selectAllCandidate(cForm));
			return mapping.findForward("listCandidate");
		}
		if ("comboSchool".equalsIgnoreCase(cForm.getTask())) {
			String city = null;

			if (cForm.getSelectOtherSchool().compareTo("yes") != 0) {
				cForm.setSchoolCity(cMan.getSchoolCity(cForm.getSchoolId()));
				city = cForm.getSchoolCity();	
			}
			response.setContentType("text/text;charset=utf-8");
			response.setHeader("cache-control", "no-cache");
			PrintWriter out = response.getWriter();
			
			if (city == null) {
				city = "";
			}
			if (cForm.getSelectOtherSchool().compareTo("yes") != 0) {
				out.write(" &nbsp; &nbsp; &nbsp;<br><input type='text' id='schCity' value=\""
						+ city + "\" readonly='true'> ");
			} else {
				request.setAttribute("displayComboScCity", "yes");
			}
			out.flush();

			return null;
		}
		
		if ("showTrainee".equalsIgnoreCase(cForm.getTask())) {
			cForm.setListTrainee(cMan.getTraineeList(cForm.getcModel()
					.getBatch()));
			response.setContentType("text/text;charset=utf-8");
			response.setHeader("cache-control", "no-cache");
			PrintWriter out = response.getWriter();
			String append = "";
			if (cForm.getListTrainee().size() != 0) {
				append += "<script type='text/javascript' src='table.js'></script><td><table border='0' width='100%' align='center'"
						+ "class='boxShadow  example table-autosort table-autofilter  table-autopage:10 table-stripeclass:alternate table-page-number:t1page table-page-count:t1pages table-filtered-rowcount:t1filtercount table-rowcount:t1allcount'"
						+ "id='t1'>"
						+ "<thead><tr class='headerBox formHeaderBackground'>"
						+ "<th colspan='2' align='center' class='table-filterable table-sortable:default'"
						+ "style='padding: 5px 7px;'>Fullname</th>"
						+ "<th align='center' class='table-filterable table-sortable:default'>User"
						+ "ID</th><th align='center' class='table-filterable table-sortable:default'>Status</th><th></th>"
						+ "</tr></thead><tbody>";
			} 
			if (cForm.getListTrainee().size() == 0) {
				append = "<tr><td>Data Not Found</td></tr>";
			}
			for (int i = 0; i < cForm.getListTrainee().size(); i++) {
				CandidateModel cModel = (CandidateModel) cForm.getListTrainee()
						.get(i);
				if ("0".equals(cModel.getActive())) {
					cModel.setActive("Inactive");
				} else {
					cModel.setActive("Active");
				}
				append += "<tr class='formListBackground'>" +
							"<td class='formListStyle' colspan='2'>" +
								"<a href='javascript:viewTrainee(" + cModel.getTraineeId() + ")'>" + 
									cModel.getFullName() + 
								"</a>" +
							"</td>" + 
							"<td class='formListStyle' width='30%'>" + cModel.getUserId() + "</td>" +
							"<td align='center' class='formListStyle' width='15%'>" + cModel.getActive() + "</td>" +
							"<td align='center' class='formListStyle'>" +
								"<a href='javascript:viewTrainee(" + cModel.getTraineeId() + ")'>" +
									"<img src='images/detailButton.png' title='view detail' style='cursor: pointer;'/>" +
								"</a>" +
							"</td>" +
						"</tr>";
			}
			if (cForm.getListTrainee().size() != 0) {
			append += "</tbody>"+
			"<tfoot><tr class='headerBox formHeaderBackground'>"+
			"<td width='75px' class='table-page:previous formListStyle' style='cursor:pointer;'>&lt;&lt; Previous</td>"+
			"<td colspan='3' class='formListStyle' style='text-align:center;'>Page <span id='t1page'></span>&nbsp;of <span id='t1pages'></span></td>"+
			"<td width='55px' align='right' class='table-page:next formListStyle' style='cursor:pointer;'>Next &gt;&gt;</td>"+								
			"</tr><tr><td colspan='5' align='center' class='headerBox formHeaderBackground'><span id='t1filtercount'></span>&nbsp;of <span id='t1allcount'></span>&nbsp;rows match filter(s)</td>"+
			"</tr></tfoot></table></td>";
			}
			out.println(append);
			out.flush();
			return null;
		} else if ("searchTrainee".equalsIgnoreCase(cForm.getTask())) {
			cForm.setListTrainee(cMan.getTraineeSearch(cForm.getKeyword(),cForm.getCategory()));
			response.setContentType("text/text;charset=utf-8");
			response.setHeader("cache-control", "no-cache");
			PrintWriter out = response.getWriter();
			String append = "";
			if (cForm.getListTrainee().size() != 0) {
				append += "<script type='text/javascript' src='table.js'></script><td><table border='0' width='100%' align='center'"
						+ "class='boxShadow  example table-autosort table-autofilter  table-autopage:10 table-stripeclass:alternate table-page-number:t1page table-page-count:t1pages table-filtered-rowcount:t1filtercount table-rowcount:t1allcount'"
						+ "id='t1'>"
						+ "<thead><tr class='headerBox formHeaderBackground'>"
						+ "<th colspan='2' align='center' class='table-filterable table-sortable:default'"
						+ "style='padding: 5px 7px;'>Fullname</th>"
						+ "<th align='center' class='table-filterable table-sortable:default'>User"
						+ "ID</th><th align='center' class='table-filterable table-sortable:default'>Status</th><th></th>"
						+ "</tr></thead><tbody>";
			} 
			
			if (cForm.getListTrainee().size() == 0) {
				append+="<tr><td align='center'>DATA NOT FOUND</tr></td>";
			}
			for (int i = 0; i < cForm.getListTrainee().size(); i++) {
				CandidateModel cModel = (CandidateModel) cForm.getListTrainee()
						.get(i);
				if ("0".equals(cModel.getActive())) {
					cModel.setActive("Inactive");
				} else {
					cModel.setActive("Active");
				}
				append += "<tr class='formListBackground'>" +
							"<td class='formListStyle' colspan='2'>" +
								"<a href='javascript:viewTrainee(" + cModel.getTraineeId() + ")'>" + 
									cModel.getFullName() + 
								"</a>" +
							"</td>" + 
							"<td class='formListStyle' width='30%'>" + cModel.getUserId() + "</td>" +
							"<td align='center' class='formListStyle' width='15%'>" + cModel.getActive() + "</td>" +
							"<td align='center' class='formListStyle'>" +
								"<a href='javascript:viewTrainee(" + cModel.getTraineeId() + ")'>" +
									"<img src='images/detailButton.png' title='view detail' style='cursor: pointer;'/>" +
								"</a>" +
							"</td>" +
						"</tr>";
			}
			if (cForm.getListTrainee().size() != 0) {
			append += "</tbody>"+
			"<tfoot><tr class='headerBox formHeaderBackground'>"+
			"<td width='75px' class='table-page:previous formListStyle' style='cursor:pointer;'>&lt;&lt; Previous</td>"+
			"<td colspan='3' class='formListStyle' style='text-align:center;'>Page <span id='t1page'></span>&nbsp;of <span id='t1pages'></span></td>"+
			"<td width='55px' align='right' class='table-page:next formListStyle' style='cursor:pointer;'>Next &gt;&gt;</td>"+								
			"</tr><tr><td colspan='5' align='center' class='headerBox formHeaderBackground'><span id='t1filtercount'></span>&nbsp;of <span id='t1allcount'></span>&nbsp;rows match filter(s)</td>"+
			"</tr></tfoot></table></td>";
			}
			out.println(append);
			out.flush();
			return null;
		}

		if (user.getUserid().compareTo("super.admin") == 0) {
		if (user.getUserid().compareTo("super.admin") != 0) {
			cForm.setcModel(cMan.selectCandidateWithOther(user.getUserid()));
			request.setAttribute("path", cForm.getcModel().getPhoto());
		} else {
			cForm.setListBatch(cMan.selectBatch());
			cForm.setListCandidate(cMan.selectAllCandidate(cForm));
		}

		return mapping.findForward("listCandidate");
		}else{
			return mapping.findForward("welcome");
		}
	}
	
	
	private String generateUserId(String name, CandidateForm cForm, CandidateManager cMan){

		String[] fullName = name.split(" ");
		Integer isUserId = 0;
		String userId = null,validUser;
		
		if (fullName.length > 1) {
			cForm.getcModel().setFirstName(fullName[0]);
			cForm.getcModel().setLastName(fullName[1]);

			if (fullName.length == 2) {
				userId = fullName[0] + "." + fullName[1];
				isUserId = cMan.isUserId(userId);
			} else if (fullName.length == 3) {
				userId = fullName[0] + "." + fullName[1].charAt(0)+ fullName[2].charAt(0);
				isUserId = cMan.isUserId(userId);
			}

		} else {
			cForm.getcModel().setFirstName(fullName[0]);
			userId = fullName[0];
			isUserId = cMan.isUserId(userId);
		}

		if (isUserId == 0) {
			validUser = userId;
		} else {
			validUser = fullName[0] + "." + fullName[0];
			isUserId = cMan.isUserId(validUser);
			if(isUserId==0){
				validUser = validUser;
			}else{
				char arr[]=fullName[1].toCharArray();
				for(int i=0;i<arr.length;i++){
					validUser = fullName[0] +"."+arr[i];
					isUserId = cMan.isUserId(validUser);
					if(isUserId==0){
						validUser = validUser;
						break;
					}
				}
				
			}
		}
		return validUser;
	}
}
